<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, target-densityDpi=medium-dpi" />
	<title>在一起！！在一起</title>
	<!-- Bootstrap 3.3.4 -->
	<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
	<!-- Font Awesome Icons -->
	<link href="/font-awesome-4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" >

	<link href="/css/app.tmp.css" rel="stylesheet" type="text/css" />
	<!-- Socket.Io.js -->
	<script src="/socket.io/socket.io.js"></script>

	<script type="text/javascript" src="/iscroll/build/iscroll.js?t=<%= moment().unix() %>"></script>
	<!-- jQuery 2.1.4 -->
    <script type='text/javascript' src='/jQuery/jQuery-2.1.4.min.js?t=<%= moment().unix() %>' /></script>
    <!-- Bootstrap 3.3.2 JS -->
	<script type='text/javascript' src='/bootstrap/js/bootstrap.min.js?t=<%= moment().unix() %>' /></script>
	<!-- Bootstrap 3.3.2 JS -->
	<script type='text/javascript' src='/moment/min/moment.min.js?t=<%= moment().unix() %>' /></script>

	<script type='text/javascript' src='/moment/min/locales.min.js?t=<%= moment().unix() %>' /></script>

</head>

<script>
var $User = {};

$User['openid']         = '<%= fans.openid %>';
$User['subscribe']      = <%=fans.subscribe%>;
$User['nickname']       = '<%=fans.nickname%>';
$User['sex']            = <%=fans.sex%>;
$User['province']       = '<%=fans.province%>';
$User['country']        = '<%=fans.country%>';
//weixin 默认头像是0 64*64 加载小头像
$User['headimgurl']     = "<%=fans.headimgurl.replace(/0$/,'64')%>";
$User['subscribe_time'] = <%=fans.subscribe_time%>;

var $MoreMsg = <%= (msgCount>perpage)? 1: 0 %>;
var $PerPage = <%= perpage %>;
var $MsgCount = <%= msgCount %>;

var socket = io();

moment.locale('zh_cn');

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);

</script>

<body>
	<div class='header'>
		<h3 class="header-title">爱的祝福</h3>
		<div class="header-tools pull-right">
			<span class="label label-warning"><span id='counter'><%= msgCount %></span> Messages</span>
		</div>
	</div>
	<div class="main-content" id='wrapper'>
		<div class='box-body chat' id='scroller'>
			<div class='loading-box'>
				<p class='text-center'><i class="fa fa-refresh"></i> 加载中...</p>
			</div>
			<%for (var i = msgData.length-1; i >= 0;  i--) { %>
			<div class="item" data-objectid=<%=msgData[i]._id%> >
				<img src="<%= msgData[i].fans.headimgurl.replace(/0$/,'64') %>">
				<p class="message">
					<a class="name" href="#"><small class="text-muted pull-right"><i class="fa fa-clock-o"></i> <%= moment(msgData[i].created_at*1000).fromNow(); %></small><%= msgData[i].fans.nickname %></a>
				</p>
				<div class="direct-chat-text">
					<%= msgData[i].message %>
				</div>
			</div>
			<% } %>
		</div>
	</div>
	<div class="footer">
		<form action="#" method="post">
			<div class="input-group">
				<input type="text" name="message" placeholder="留下祝福吧，亲..." class="form-control"/>
				<span class="input-group-btn">
					<button type="submit" class="btn btn-warning btn-flat">发送</button>
				</span>
			</div>
		</form>
	</div>
<script>

	var myScroll = new IScroll('#wrapper', {
		mouseWheel: true,
		click: true,
	});

	var scrollToid;

	$('form').submit(function(){
		var msgText = $('input[name=message]').val();
		if(msgText != ''){
			var param = {
				openid : $User['openid'],
				msgText : msgText
			}
			param = JSON.stringify(param);

			//var param = '{"openid":'+$User['openid'],'code':''}';
			socket.emit('send msg', param);
			$('input[name=message]').val('');
			$('input[name=message]').blur();
		}
		
		return false;
	});

	socket.on('send msg', function(msgData){
		//加载
		$('.box-body').append(getMsgItemTpl(msgData));
		//消息总数加1
		$MsgCount++;
		$('#counter').html($MsgCount);

		// 是本人发送的消息 或者 滚动条在最下方 消息加载后滚动条处于最下方
		if(msgData[0].fans.openid == $User['openid'] || myScroll.y == myScroll.maxScrollY) {
			var objectid = $('.item:last').attr('data-objectid');
			// dom 刷新 重新加载滚动条
			myScroll.refresh();
			//滚动条到最下方
			myScroll.scrollTo(0,myScroll.maxScrollY);

		}
	});

	socket.on('load more', function(msgData){

		$('.loading-box').hide();
		//如果最后一页 设置滚动标记为false
		if(msgData.length <= $PerPage)
			$MoreMsg = false;
		else
			msgData.pop();

		if(msgData.length){

			$('.loading-box').after(getMsgItemTpl(msgData));
			//滚动加载
			myScroll.refresh();
			myScroll.scrollToElement(document.querySelector(".item[data-objectid='"+scrollToid+"']"),0);

		}

	})

	myScroll.on('scrollEnd', function(){
		//最有一页 不触发滚动事件
		if( !$MoreMsg ){
			return false;
		}
		//滚动到头部
		if( myScroll.y >=0 ){
			$('.loading-box').show();
			scrollToid = $('.item:first').attr('data-objectid');

			var param = {
				_id : scrollToid,
			}

			function _doemit(param)  {
				return function() {
					socket.emit('load more', param);
				}
			}

			window.setTimeout(_doemit(param),500);
		}

	});


	function getMsgItemTpl(msgData){

		var i;
		var itemTpl='';


		for(i = msgData.length-1; i >=0 ; i--){

			msgData[i].created_at = moment(msgData[i].created_at*1000).fromNow();

			itemTpl += "<div class=\"item\" data-objectid="+msgData[i]._id+" >";
			itemTpl += "<img src=\""+msgData[i].fans.headimgurl.replace(/0$/,'64')+"\">";
			itemTpl += "<p class=\"message\">";
			itemTpl += "<a class=\"name\" href=\"#\"><small class=\"text-muted pull-right\"><i class=\"fa fa-clock-o\"></i> "+msgData[i].created_at+"</small>"+ msgData[i].fans.nickname +"</a>";
			itemTpl += "</p>";
			itemTpl += "<div class=\"direct-chat-text\">"+msgData[i].message+"</div>";
			itemTpl += "</div>";
		}

		return itemTpl;
	}
</script>
</body>

</html>
